package ws

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

type Message struct {
	FromId  string `json:"from_id"` //发送的id
	ToId    string `json:"to_id"`   //发送给谁的id
	Content string `json:"content"` //发送的内容
	IsRead  bool   `json:"isRead"`
	Time    string `json:"time"` //发送的时间
}

var offlineMessages = make(map[string][]Message)

var clients = make(map[string]*websocket.Conn) // connected clients

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// 建立client连接
func HandleConnections(ctx *gin.Context) {
	id := ctx.Query("id")

	ws, _ := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)

	defer ws.Close()

	clients[id] = ws

	// When a client connects, send any offline messages
	if messages, ok := offlineMessages[id]; ok {
		for _, msg := range messages {
			msg.IsRead = false
			if err := ws.WriteJSON(msg); err != nil {
				break
			}
		}
		delete(offlineMessages, id)
	}

	for {
		var msg Message

		err := ws.ReadJSON(&msg)
		msg.IsRead = false
		if err != nil {
			delete(clients, id)
			break
		}

		if toClient, ok := clients[msg.ToId]; ok {
			if err := toClient.WriteJSON(msg); err != nil {
				toClient.Close()
				delete(clients, msg.ToId)
			}
		} else {
			offlineMessages[msg.ToId] = append(offlineMessages[msg.ToId], Message{FromId: msg.FromId, Content: msg.Content})
		}
	}
}
